package com.example.testcalendaractivity;


import static com.example.testcalendaractivity.util.SharedValues.MAX_DESCRIPTION_LENGTH;
import static com.example.testcalendaractivity.util.SharedValues.MAX_EVENT_NUMBER;
import static com.example.testcalendaractivity.util.SharedValues.MAX_TITLE_LENGTH;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.testcalendaractivity.util.SharedValues;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class AddEventActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "yebinger";
    private EditText eventTitle;
    private EditText eventContent;
    private EditText eventLocation;
    private Button btnSave;
    private Calendar calendar = Calendar.getInstance();
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    private TextView dateTextStart;
    private TextView dateTextEnd;
    private Button btnBcak;
    private static String calanderURL = "content://com.android.calendar/calendars";
    private static String calanderEventURL = "content://com.android.calendar/events";
    private static String calanderRemiderURL = "content://com.android.calendar/reminders";

    private RadioGroup freqPick;
    private Button btnDelete;
    private Button pickButton;
    private Button pickButtonEnd;




    @SuppressLint({"WrongViewCast", "CutPasteId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_event);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            Log.e("Permission error", "You need permission");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, 1);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            Log.e("Permission error", "You need permission");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR}, 1);
        }

        eventTitle = findViewById(R.id.eventTitle);
        eventContent = findViewById(R.id.eventContent);
        pickButton = findViewById(R.id.pick_button);
        btnSave = findViewById(R.id.btn_save);
        btnBcak = findViewById(R.id.back_button);
        btnDelete = findViewById(R.id.btn_delete);
        dateTextStart = findViewById(R.id.date_text);
        dateTextEnd = findViewById(R.id.date_text_end);
        pickButtonEnd = findViewById(R.id.pick_button_end);
        eventLocation = findViewById(R.id.textEventLocation);
        freqPick = findViewById(R.id.rg1);

        // 初始化事件起止时间
        Bundle bundle = getIntent().getExtras();
        int year = bundle.getInt("year");
        int month = bundle.getInt("month");
        int day = bundle.getInt("day");
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH,day);
        dateTextStart.setText(DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
        dateTextEnd.setText(DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));

        //文本框字数监听
        eventTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {  }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > MAX_TITLE_LENGTH) {
                    s.delete(MAX_TITLE_LENGTH, s.length()); // 删除超出部分
                }
            }
        });

        //设置事件备注字数监听
        eventContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > MAX_DESCRIPTION_LENGTH) {
                    s.delete(MAX_DESCRIPTION_LENGTH, s.length()); // 删除超出部分
                }
            }
        });

        // 设置时间选择按钮的点击事件
        dateTextStart.setOnClickListener(this);
        pickButton.setOnClickListener(this);
        dateTextEnd.setOnClickListener(this);
        pickButtonEnd.setOnClickListener(this);
        //删除按钮清空文本框
        btnDelete.setOnClickListener(this);
        // 保存按钮点击事件
        btnSave.setOnClickListener(this);
        btnBcak.setOnClickListener(this);

        queryEvent();

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pick_button || v.getId() == R.id.date_text || v.getId() == R.id.pick_button_end || v.getId() == R.id.date_text_end) {
            datePick(v);
        } else if (v.getId() == R.id.btn_delete) {
            clearEditTexts();
        } else if (v.getId() == R.id.btn_save) {
            try {
                saveEvent();
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else if (v.getId() == R.id.back_button) {
            finish();
        }

    }

    private void datePick(View v) {

        Bundle bundle = getIntent().getExtras();
        int year = bundle.getInt("year");
        int month = bundle.getInt("month");
        int day = bundle.getInt("day");

        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);

        DatePickerDialog datePickerDialog = new DatePickerDialog(AddEventActivity.this,
                (view, year1, monthOfYear, dayOfMonth) -> {
                    // 设置时间到时间选择器
                    TimePickerDialog timePickerDialog = new TimePickerDialog(AddEventActivity.this,
                            (view1, hourOfDay, minute1) -> {
                                // 这里可以更新界面显示选择的时间
                                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                calendar.set(Calendar.MINUTE, minute1);
                                calendar.set(Calendar.YEAR, year1);
                                calendar.set(Calendar.MONTH, monthOfYear);
                                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                if (v.getId() == R.id.date_text || v.getId() == R.id.pick_button) {
                                    dateTextStart.setText(DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));
                                    start.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                    start.set(Calendar.MINUTE, minute1);
                                    start.set(Calendar.YEAR, year1);
                                    start.set(Calendar.MONTH, monthOfYear);
                                    start.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    if (end.before(start)) {
                                        dateTextEnd.setText(DateFormat.format("yyyy-MM-dd HH:mm", start.getTime()));
                                    }
                                } else if (v.getId() == R.id.date_text_end || v.getId() == R.id.pick_button_end) {
                                    end.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                    end.set(Calendar.MINUTE, minute1);
                                    end.set(Calendar.YEAR, year1);
                                    end.set(Calendar.MONTH, monthOfYear);
                                    end.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    if (calendar.before(start)) {
                                        dateTextEnd.setText(DateFormat.format("yyyy-MM-dd HH:mm", start.getTime()));
                                    } else dateTextEnd.setText(DateFormat.format("yyyy-MM-dd HH:mm", calendar.getTime()));
                                }
                            }, hour, minute, true);
                    timePickerDialog.show();
                }, year, month, day);
        datePickerDialog.getDatePicker().setMinDate(now.getTimeInMillis());
        datePickerDialog.show();
    }

    private void clearEditTexts() {
        // 获取当前Activity中的所有EditText
        List<EditText> editTexts = getEditableFields(this);
        dateTextStart.setText("请选择开始时间");
        dateTextEnd.setText("请选择结束时间");
        // 遍历并清空每个EditText的内容
        for (EditText editText : editTexts) {
            editText.setText("");
        }
    }
    /**
     * 获取Activity中的所有EditText
     * @param activity 当前Activity
     * @return 所有的EditText列表
     */
    private List<EditText> getEditableFields(Activity activity) {
        List<EditText> editTexts = new ArrayList<>();
        View view = activity.getWindow().getDecorView();
        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                if (child instanceof EditText) {
                    editTexts.add((EditText) child);
                } else if (child instanceof ViewGroup) {
                    editTexts.addAll(getEditableFieldsFromViewGroup((ViewGroup) child));
                }
            }
        }
        return editTexts;
    }

    /**
     * 递归获取ViewGroup中的所有EditText
     * @param vg ViewGroup
     * @return 所有的EditText列表
     */
    private List<EditText> getEditableFieldsFromViewGroup(ViewGroup vg) {
        List<EditText> editTexts = new ArrayList<>();
        for (int i = 0; i < vg.getChildCount(); i++) {
            View child = vg.getChildAt(i);
            if (child instanceof EditText) {
                editTexts.add((EditText) child);
            } else if (child instanceof ViewGroup) {
                editTexts.addAll(getEditableFieldsFromViewGroup((ViewGroup) child));
            }
        }
        return editTexts;
    }

    @SuppressLint("Range")
    private void saveEvent() throws ParseException {

        //查询所选择起始日期的事件数是否已达上限
        if (ifEventReachedMax()) {
            return;
        }
        //读取系统日历账户，如果为0的话先添加
        getUserCursor();
        // 标题必填
        if (eventTitle.getText().toString().isEmpty()) {
            Toast.makeText(this, "请输入事件标题！", Toast.LENGTH_LONG).show();
            return;
        }

        // 添加事件
        addEvents();
        //查询事件
//        queryEvent();
    }


    private boolean ifEventReachedMax() throws ParseException {

        String dateString = dateTextStart.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.getDefault());

        Calendar beginTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));  // Calendar类处理日期和时间.这里注意时区！
        beginTime.setTimeInMillis(dateFormat.parse(dateString).getTime());
        beginTime.set(Calendar.HOUR_OF_DAY, 0);
        beginTime.set(Calendar.MINUTE,0);
        beginTime.set(Calendar.SECOND,0);
        long startMillis = beginTime.getTimeInMillis(); //获取19701月1日至今的毫秒数

        Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        endTime.setTimeInMillis(dateFormat.parse(dateString).getTime());
        endTime.set(Calendar.HOUR_OF_DAY, 23);
        endTime.set(Calendar.MINUTE,59);
        endTime.set(Calendar.SECOND,59);
        long endMillis = endTime.getTimeInMillis();

        // 构建 Instances URI，设置查询范围
        Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
        ContentUris.appendId(builder, startMillis);
        ContentUris.appendId(builder, endMillis);

        // 查询字段，包括 ORIGINAL_ID
        String[] projection = new String[]{
                CalendarContract.Instances.EVENT_ID,
                CalendarContract.Instances.BEGIN,
                CalendarContract.Instances.TITLE,
        };

        // 筛选条件
        String selection = "(" + CalendarContract.Instances.BEGIN + " >= ?) AND (" + CalendarContract.Instances.BEGIN + " <= ?) AND (" + CalendarContract.Instances.OWNER_ACCOUNT + " = ?)";
        String[] selectionArgs = new String[]{String.valueOf(startMillis - 1000), String.valueOf(endMillis), "ADBC_calendar"};
        ContentResolver cr = getContentResolver(); // 访问其他应用的数据——包括联系人、日历、媒体库等
        Cursor cursor = cr.query(builder.build(), projection, selection, selectionArgs, null);

        if (cursor != null) {
            //Toast.makeText(this, "事件数量：" + cursor.getCount(), Toast.LENGTH_SHORT).show();
            if (cursor.getCount() >= MAX_EVENT_NUMBER) {
                Toast.makeText(this, "所选日期事件数量已达上限！", Toast.LENGTH_SHORT).show();
                return true;
            } else return false;
        }
        return false;
    }

    @SuppressLint("Range")
    private void queryEvent() {
        // 定义要查询的列
        String[] projection = {
                CalendarContract.Events._ID,               // 事件 ID
                CalendarContract.Events.TITLE,             // 事件标题
                CalendarContract.Events.DTSTART,           // 事件开始时间
                CalendarContract.Events.DTEND,             // 事件结束时间
                CalendarContract.Events.DESCRIPTION,        // 事件描述
                CalendarContract.Events.EVENT_LOCATION,       // 事件地点
                CalendarContract.Events.RRULE,
                CalendarContract.Events.ORIGINAL_ID
        };

        // 执行查询
        Cursor cursor = getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, null, null, null);
        //处理查询数据
        if (cursor != null && cursor.moveToFirst()) {
            do {
                // 从 Cursor 中获取数据
                long eventId = cursor.getLong(cursor.getColumnIndex(CalendarContract.Events._ID));
                String title = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE));
                long startTime = cursor.getLong(cursor.getColumnIndex(CalendarContract.Events.DTSTART));
                long endTime = cursor.getLong(cursor.getColumnIndex(CalendarContract.Events.DTEND));
                String description = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION));
                String loaction = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION));
                String rule = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.RRULE));
                long originId = cursor.getLong(cursor.getColumnIndex(CalendarContract.Events.ORIGINAL_ID));

                // 将时间戳转换为日期格式（可选）
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date startDate = new Date(startTime);
                Date endDate = new Date(endTime);
                String formattedStartDate = sdf.format(startDate);
                String formattedEndDate = sdf.format(endDate);

                // 处理每条记录
                Log.d("EventDetails", "Event ID: " + eventId + ", Title: " + title +
                        ", Start Time: " + formattedStartDate + ", End Time: " + formattedEndDate +
                        ", Description: " + description + ", event_location: " + loaction +
                        ", RRULE: " + rule + ", originId: " + originId);

            } while (cursor.moveToNext());
        }
        if (cursor != null) {
            cursor.close(); // 关闭 Cursor
        }
    }

    @SuppressLint("Range")
    private void getUserCursor() {

        //获取指定账户ADBC_calendar
        String[] selectionArgs = new String[]{"ADBC_calendar"};
        String[] projection1 = new String[]{CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME};
        String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ?";
        Cursor userCursor = getContentResolver().query(Uri.parse(calanderURL), projection1, selection, selectionArgs, null);
        System.out.println("Count: " + userCursor.getCount());

        if (userCursor.getCount() == 0) {
            // 添加账户
            TimeZone timeZone = TimeZone.getDefault(); //默认时区
            ContentValues value = new ContentValues();  // ContentValues可以存储键值对
            value.put(CalendarContract.Calendars.NAME, "ADBC_calendar");
            value.put(CalendarContract.Calendars.ACCOUNT_NAME, "ADBC_calendar");
            value.put(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.local");
            value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, "calendar");
            value.put(CalendarContract.Calendars.VISIBLE, 1);
            value.put(CalendarContract.Calendars.CALENDAR_COLOR, -9206951);
            value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
            value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
            value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
            value.put(CalendarContract.Calendars.OWNER_ACCOUNT, "ADBC_calendar");
            value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);
            Uri calendarUri = CalendarContract.Calendars.CONTENT_URI;
            calendarUri = calendarUri.buildUpon()
                    .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                    .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, "ADBC_calendar")
                    .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.local")
                    .build();

            getContentResolver().insert(calendarUri, value);
        }

        //System.out.println("name: " + userCursor.getString(userCursor.getColumnIndex("ACCOUNT_NAME")));
        if (userCursor.moveToFirst()) {
            String userName0 = userCursor.getString(userCursor.getColumnIndexOrThrow(CalendarContract.Calendars.ACCOUNT_NAME));
            Log.i(TAG, "saveEvent: ACCOUNT_NAME: " + userName0);
        }
        userCursor.close();

        return;
    }

    @SuppressLint("Range")
    private void addEvents() throws ParseException {
        String title = eventTitle.getText().toString();
        String content = eventContent.getText().toString();
        String location = eventLocation.getText().toString();

        //将日期转化为时间戳
        String stime = dateTextStart.getText().toString();
        String dtime = dateTextEnd.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long timeStart = dateFormat.parse(stime).getTime();
        long timeEnd = dateFormat.parse(dtime).getTime();
        int repeatOptionId = freqPick.getCheckedRadioButtonId();
        ContentResolver cr = getContentResolver();


        //获取指定账户ADBC_calendar
        String[] selectionArgs = new String[]{"ADBC_calendar"};
        String[] projection1 = new String[]{CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME};
        String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ?";
        Cursor cursor0 = null;
        long calendarId = -1;
        try {
            cursor0 = cr.query(
                    CalendarContract.Calendars.CONTENT_URI,
                    projection1,
                    selection,
                    selectionArgs,
                    null
            );
            if (cursor0 != null && cursor0.moveToFirst()) {
                calendarId = cursor0.getLong(0);
            }
        } finally {
            if (cursor0 != null) {
                cursor0.close();
            }
        }
        // 插入数据存放在event对象中
        ContentValues event = new ContentValues();
        event.put(CalendarContract.Events.TITLE, title);
        event.put(CalendarContract.Events.DESCRIPTION, content);
        event.put(CalendarContract.Events.CALENDAR_ID, calendarId);
        System.out.println("calId: " + calendarId);
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai");
        event.put(CalendarContract.Events.EVENT_LOCATION, location);
        event.put(CalendarContract.Events.DTSTART, timeStart);
        event.put(CalendarContract.Events.DTEND, timeEnd);
        event.put(CalendarContract.Events.HAS_ALARM, 1); //有提醒

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(timeStart);
        calendar.add(Calendar.YEAR, 10); // 加上10年

        // 使用 SimpleDateFormat 生成符合 iCalendar 规范的 UNTIL 时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.getDefault());
        // 设置 SimpleDateFormat 的时区为 UTC
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String untilDate = sdf.format(calendar.getTime());
        //String untilDate = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'").format(calendar.getTime());

        if (repeatOptionId == R.id.btn_daily1) {
            event.put(CalendarContract.Events.RRULE, "FREQ=DAILY");
        } else if (repeatOptionId == R.id.btn_weekly1) {
            event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY");
        } else if (repeatOptionId == R.id.btn_monthly1) {
            event.put(CalendarContract.Events.RRULE, "FREQ=MONTHLY");
        } else if (repeatOptionId == R.id.btn_yearly1) {
            event.put(CalendarContract.Events.RRULE, "FREQ=YEARLY");
        }

        //添加事件
        Uri newEvent = cr.insert(Uri.parse(calanderEventURL), event);
        //事件提醒
        long id = Long.parseLong(newEvent.getLastPathSegment());
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Reminders.EVENT_ID, id);
        // 提前10分钟有提醒
        values.put("minutes", 0);
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);

        getContentResolver().insert(Uri.parse(calanderRemiderURL), values);
        //Toast.makeText(AddEventActivity.this, "插入事件成功!!!", Toast.LENGTH_LONG).show();

        Intent resultIntent = new Intent();
        resultIntent.putExtra("selectedDate", timeStart);
        setResult(RESULT_OK,resultIntent);
        finish();
    }
}